package permission

import (
	"context"
	"fmt"
	"github.com/samber/lo"
	"private-domain-overseas-service/admin/business/api/internal/repository/permission"
	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"
	"private-domain-overseas-service/pkg/common"
	"private-domain-overseas-service/pkg/status/bizadmin"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/adminrole"
	"private-domain-overseas-service/tools/ent/adminrouter"
	"private-domain-overseas-service/tools/ent/adminuser"
	"private-domain-overseas-service/tools/ent/predicate"
	"strconv"
	"strings"

	"github.com/zeromicro/go-zero/core/logx"
)

type AdminUserInfoLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewAdminUserInfoLogic - 获取用户信息
func NewAdminUserInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminUserInfoLogic {
	return &AdminUserInfoLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AdminUserInfoLogic) AdminUserInfo() (resp *types.AdminUserInfoResponse, err error) {
	adminRouterDao := permission.NewAdminRouterDao(l.ctx, l.svcCtx)
	adminRoleDao := permission.NewAdminRoleDao(l.ctx, l.svcCtx)
	adminUserDao := permission.NewAdminUserDao(l.ctx, l.svcCtx)

	// 用户id
	userId := common.JwtAdminAuthUserId(l.ctx)
	roleIds := common.JwrAdminAuthRoleId(l.ctx)

	// 根据用户id查用户
	adminUserConditions := make([]predicate.AdminUser, 0, 2)
	adminUserConditions = append(adminUserConditions, adminuser.IDEQ(int(userId)))
	adminUserConditions = append(adminUserConditions, adminuser.IsDeleteEQ(bizadmin.NotDelete))
	adminUser, err := adminUserDao.AdminUserFirst(adminUserConditions)
	if err != nil {
		if !ent.IsNotFound(err) {
			return nil, xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("查询用户信息失败: %v", err.Error()))
		} else {
			return nil, xerr.ErrCodeMsg(xerr.ServerAdminUserNotExist, fmt.Sprintf("用户不存在: %v", err.Error()))
		}
	}

	// 查询角色信息
	adminRoleConditions := make([]predicate.AdminRole, 0, 1)
	adminRoleConditions = append(adminRoleConditions, adminrole.IDIn(roleIds...))
	adminRoles, err := adminRoleDao.AdminRoleConditionsAll(adminRoleConditions)
	if err != nil {
		return nil, xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("查询角色信息失败: %v", err.Error()))
	}

	// 取出角色名称（前端使用）
	adminRolesInfo := lo.Map(adminRoles, func(item *ent.AdminRole, _ int) string {
		return item.AdminRoleName
	})

	// 获取按钮id
	routerIds := lo.Map(adminRoles, func(item *ent.AdminRole, _ int) []int {
		return lo.Map(strings.Split(item.AdminRoleRouterIds, ","), func(routers string, _ int) int {
			id, _ := strconv.Atoi(routers)
			return id
		})
	})

	// 二维数组转一维 去重
	routerIdsArr := lo.Flatten(routerIds)
	uniqRouterIds := lo.Uniq(routerIdsArr)

	// 查询所有按钮
	adminRouterConditions := make([]predicate.AdminRouter, 0, 3)
	adminRouterConditions = append(adminRouterConditions, adminrouter.AdminRouterMenuTypeEQ(bizadmin.TypeButton))
	adminRouterConditions = append(adminRouterConditions, adminrouter.AdminRouterStatusEQ(bizadmin.StatusEnabled))
	adminRouterConditions = append(adminRouterConditions, adminrouter.IDIn(uniqRouterIds...))
	adminButtons, _, err := adminRouterDao.AdminRouterConditionsAll(adminRouterConditions)
	if err != nil {
		return nil, xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("获取用户按钮失败: %v", err.Error()))
	}

	// 取出按钮名称（前端使用）
	buttons := lo.Map(adminButtons, func(item *ent.AdminRouter, _ int) string {
		return item.AdminRouterRouteName
	})

	// 返回数据
	resp = &types.AdminUserInfoResponse{
		UserID:   userId,
		UserName: adminUser.AdminUserUsername,
		Roles:    adminRolesInfo,
		Buttons:  buttons,
		NickName: adminUser.AdminUserNickname,
		Email:    adminUser.AdminUserEmail,
	}
	return
}
